//
//  OAuthViewController.swift
//  新浪微博
//
//  Created by yaozhen on 2017/12/11.
//  Copyright © 2017年 ZYZ. All rights reserved.
//

import UIKit
import SVProgressHUD
//通过webview加载新浪微博授权界面
class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        //设置代理
        webView.delegate = self
        //取消滚动视图
        webView.scrollView.isScrollEnabled = false
        
        title = "新浪微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", fontSize: 16, target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "自动填充", target: self, action: #selector(autoFill))
    }
    @objc private func close(){
        dismiss(animated: true, completion: nil)
            }
    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(RedirectURl)"
        guard let url = URL.init(string: urlString) else {
            return
        }
        let request = URLRequest.init(url: url)
        webView.loadRequest(request)
        
    }
    //自动填充，--webview的注入 通过js修改本地浏览器中的缓存界面
    //点击登录按钮，执行submit 将本地数据提交到服务器
    @objc private func autoFill(){
        let js = "document.getElementById('userId').value = '18721970171';" + "document.getElementById('passwd').value = 'zou123456'"
        //webview执行js
        webView.stringByEvaluatingJavaScript(from: js)
        
    }


}
extension OAuthViewController: UIWebViewDelegate {
    //将要加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果请求地址包含 http://baidu.com 不加载数据
        if request.url?.absoluteString.hasPrefix(RedirectURl) == false {
            return true
        }
        //确认思路
        //1 如果请求地址包含http://baidu.com 不加载页面/ 否则加载页面
        //2从 http://www.baidu.com 回调地址查询字符串中查找code =
        //  如果有授权成功没有授权失败
        print("加载请求----\(String(describing: request.url?.absoluteURL))")
        
        //query 就是字符串后面的所有部分
        
        if request.url?.query?.hasPrefix("code=") == false{
            return false
        }
        
        print("加载请求 --- \(String(describing: request.url?.query))")
        //代码走到此处一定有查询字符串
        let code = request.url?.query?.substring (from: "code=".endIndex) ?? ""

//        print("授权码----\(code)")

        NetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else {
//                SVProgressHUD.showInfo(withStatus: "登录成功")
                //登录成功回调 如果跳转 通过通知发送消息
                //1发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserLoginSuccesedNotifaication), object: nil)
                //2 关闭窗口
                self.close()
            }
        }
        
        return true
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
